package com.mayikt.controller;

import com.alibaba.fastjson.JSONObject;
import com.mayikt.entity.OrderEntity;
import com.mayikt.mapper.OrderMapper;
import org.omg.CORBA.ORB;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.awt.font.ShapeGraphicAttribute;

/**
 * @author 蚂蚁课堂创始人-余胜军QQ644064779
 * @title: DeadLetterController
 * @description: 每特教育独创第五期互联网架构课程
 * @date 2019/12/1221:29
 */
@RestController
public class DeadLetterController {
    @Autowired
    private RabbitTemplate rabbitTemplate;
    /**
     * 订单交换机
     */
    @Value("${mayikt.order.exchange}")
    private String orderExchange;

    @Autowired
    private OrderMapper orderMapper;
    /**
     * 订单路由key
     */
    @Value("${mayikt.order.routingKey}")
    private String orderRoutingKey;

    @RequestMapping("/sendOrderMsg")
    public String sendOrderMsg() {
        // 1.生产订单id
        String orderId = System.currentTimeMillis() + "";
        String orderName = "蚂蚁课堂第六期报名";
        OrderEntity orderEntity = new OrderEntity(orderName, orderId);
        String msg = JSONObject.toJSONString(orderEntity);
        sendMsg(msg);
        return orderId;
        // 后期客户端主动使用orderId调用服务器接口 查询该订单id是否在数据库中存在数据 消费成功 消费失败
    }

    @Async
    public void sendMsg(String msg) {
        rabbitTemplate.convertAndSend(orderExchange, orderRoutingKey, msg,
                new MessagePostProcessor() {
                    @Override
                    public Message postProcessMessage(Message message) throws AmqpException {
                        message.getMessageProperties().setExpiration("10000");
                        return message;
                    }
                });
        // 消息投递失败
    }

    /**
     * 主动查询接口
     * 先查询该订单的消息是否投递失败
     * 在查询数据库
     */

    @RequestMapping("getOrder")
    public Object getOrder(String orderId) {
        OrderEntity orderEntity = orderMapper.getOrder(orderId);
        if (orderEntity == null) {
            return "消息正在异步的处理中";
        }
        return orderEntity;
    }
}
